import { _auth } from '../../common/api/signin'
const app = getApp()
Page({
  data: {},
  auth(e) {
    app.loading('加载中')
    let { iv, encryptedData } = e.detail
    wx.checkSession({
      success: () => {
        console.log('登录未过期')
        let session_key = wx.getStorageSync('session_key')
        _auth(session_key, iv, encryptedData).then(res => {
          if (res.data.IsSuccess) {
            wx.hideLoading()
            let uid = res.data.Data.unionId
            wx.setStorageSync('uid', uid)
            wx.redirectTo({
              url: '/pages/index/index'
            })
          }
        }).catch(err => {
          wx.hideLoading()
          console.log(err)
        })
      },
      fail: () => {
        console.log('登录已过期，重新登录')
        wx.login({
          success: r => {
            _login(r.code).then(res => {
              if (res.data.IsSuccess) {
                wx.setStorageSync('session_key', res.data.Data.session_key)
                let session_key = wx.getStorageSync('session_key')
                _auth(session_key, iv, encryptedData).then(res => {
                  if (res.data.IsSuccess) {
                    wx.hideLoading()
                    let uid = res.data.Data.unionId
                    wx.setStorageSync('uid', uid)
                    wx.redirectTo({
                      url: '/pages/index/index'
                    })
                  }
                }).catch(err => {
                  wx.hideLoading()
                  console.log(err)
                })
              } else {
                wx.hideLoading()
                wx.showModal({
                  title: '对不起',
                  content: res.data.Data,
                  showCancel: false
                })
              }
            }).catch(err => {
              wx.hideLoading()
              console.log(err)
            })
          }
        })
      }
    })
  }
})